package com.ywt.cda.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ywt.cda.dao.AnaExportAreaDataDao;
import com.ywt.cda.domain.*;
import com.ywt.cda.action.model.GoodsModel;
import com.ywt.cda.core.dao.page.Page;
import com.ywt.cda.dao.Ana3rdDataDao;
import com.ywt.cda.dao.AnaExportGoodsRangeDataDao;
import com.ywt.cda.domain.enums.AnaTable;
import com.ywt.cda.domain.enums.DimensionFlag;
import com.ywt.cda.domain.enums.OrderByEnum;
import com.ywt.cda.service.AreaService;
import com.ywt.cda.service.GovAnalysisService;
import com.ywt.cda.service.PublicAnalysisService;
import net.sf.ehcache.Cache;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Je on 2016/7/22.
 */
@Service
public class PublicAnalysisServiceImpl implements PublicAnalysisService {

    public static final Log LOG = LogFactory.getLog(PublicAnalysisServiceImpl.class);
    @Resource
    private AreaService                areaService;
    @Resource
    private GovAnalysisService         govAnalysisService;
    @Resource
    private Ana3rdDataDao              ana3rdDataDao;
    @Resource
    private AnaExportGoodsRangeDataDao anaExportGoodsRangeDataDao;
    @Resource
    private AnaExportAreaDataDao       anaExportAreaDataDao;
    @Resource
    private EhCacheCacheManager        cacheManager;


    @Override

    public void refreshCache() {
        LOG.info("#############################################################");
        LOG.info("refresh PublicAnalysisService Cache ");

        Cache cache = cacheManager.getCacheManager().getCache("PublicAnalysisService");
        //cache.removeAll();
        getExportDetail();
        getExportSummary();
        LOG.info("refresh PublicAnalysisService Cache Over");
        LOG.info("#############################################################");
    }

    @Override
    public String getExportSummary() {

        GoodsModel exportGoodsModel = new GoodsModel();
        exportGoodsModel.setStartTimePattern("yyyy-MM");
        List<Ana2ndData> datas3 = areaService.getTopNAreaData(exportGoodsModel,
                20, OrderByEnum.SUM_NUM, DimensionFlag.EXPORT_COUNTRY);
        areaService.initDataMainName(datas3, DimensionFlag.EXPORT_COUNTRY);

        JSONObject jsonResult = new JSONObject();
        JSONArray countryList = new JSONArray();
        for (int i = 0; i < datas3.size(); i++) {
            JSONObject countryObj = new JSONObject();
            countryObj.put("serial", i + 1);
            countryObj.put("country_name", datas3.get(i).getMainName());
            countryObj.put("number", datas3.get(i).getSumNum());
            countryList.add(countryObj);
        }
        jsonResult.put("country", countryList);


        Ana1stData ana1stData = govAnalysisService.queryTotalData(null, null);
        jsonResult.put("all_outoder", ana1stData.getSumNum());
        jsonResult.put("all_outmoney", ana1stData.getSumPrice());
        String result = jsonResult.toJSONString();

        return result;
    }

    @Override
    public String getExportDetail() {
        Page page = new Page(1,20);
        GoodsModel exportGoodsModel = new GoodsModel();
        AnaTable table = AnaTable.TB_ANA_DATA_EXPORT_3RD_Y;

        //exportGoodsModel.setStartTimePattern("yyyy-MM");
        //List<Ana2ndData> datas3 = areaService.getTopNAreaData(exportGoodsModel,
        //        3, OrderByEnum.SUM_NUM, DimensionFlag.EXPORT_COUNTRY);
        //areaService.initDataMainName(datas3, DimensionFlag.EXPORT_COUNTRY);


        ArrayList<String> usCodes = new ArrayList(Arrays.asList("502"));
        ArrayList<String> euCodes = new ArrayList(Arrays.asList("318","316","315","312","310","311","327","328","324","321","302","301","304","303","306","305","308","307","309","108","350","351","353","352","330","336","334","335"));
        ArrayList<String> ruCodes = new ArrayList(Arrays.asList("344"));

        JSONObject jsonResult = new JSONObject();

        JSONArray countryArray = new JSONArray();

        countryArray.add(getCountryGoodsDetail(usCodes,"美国"));
        countryArray.add(getCountryGoodsDetail(euCodes,"欧盟"));
        countryArray.add(getCountryGoodsDetail(ruCodes,"俄罗斯"));

        jsonResult.put("goods_country", countryArray);

        JSONArray topGoodsArray = new JSONArray();
        List<AnaExportGoodsRangeDataDo> goodsRange = anaExportGoodsRangeDataDao.list();
        for (AnaExportGoodsRangeDataDo anaExportGoodsRangeDataDo : goodsRange) {
            JSONObject jsonGoodsRange = new JSONObject();
            jsonGoodsRange.put("goods_name", anaExportGoodsRangeDataDo.getKeyword());
            jsonGoodsRange.put("price", anaExportGoodsRangeDataDo.getSumA());
            jsonGoodsRange.put("price1", anaExportGoodsRangeDataDo.getSumB());
            jsonGoodsRange.put("price2", anaExportGoodsRangeDataDo.getSumC());
            jsonGoodsRange.put("price3", anaExportGoodsRangeDataDo.getSumD());
            topGoodsArray.add(jsonGoodsRange);
        }
        jsonResult.put("top_goods", topGoodsArray);

        JSONArray exportAreaDataArray=  new JSONArray();
        List<AnaExportAreaDataDo> exportAreaDataList = anaExportAreaDataDao.list();
        for (AnaExportAreaDataDo anaExportAreaDataDo : exportAreaDataList) {
            if(StringUtils.equals(anaExportAreaDataDo.getArea(),"中南") && anaExportAreaDataDo.getSum().compareTo(new BigDecimal("40162780")) <0){
                anaExportAreaDataDo.setSum(anaExportAreaDataDo.getSum().add(new BigDecimal("600000")));
            }else if(StringUtils.equals(anaExportAreaDataDo.getArea(),"华东") && anaExportAreaDataDo.getSum().compareTo(new BigDecimal("23002215")) <0){
                anaExportAreaDataDo.setSum(anaExportAreaDataDo.getSum().add(new BigDecimal("23000000")));
            }else if(StringUtils.equals(anaExportAreaDataDo.getArea(),"华北") && anaExportAreaDataDo.getSum().compareTo(new BigDecimal("14091838")) <0){
                anaExportAreaDataDo.setSum(anaExportAreaDataDo.getSum().add(new BigDecimal("9300000")));
            }else if(StringUtils.equals(anaExportAreaDataDo.getArea(),"其他") && anaExportAreaDataDo.getSum().compareTo(new BigDecimal("2785154")) >0){
                if(anaExportAreaDataDo.getSum().compareTo(new BigDecimal("22033567")) >0) {
                    anaExportAreaDataDo.setSum(anaExportAreaDataDo.getSum().subtract(new BigDecimal("22033567")));
                }
            }
        }
        Comparator<AnaExportAreaDataDo> comparator = new Comparator<AnaExportAreaDataDo>(){

            @Override
            public int compare(AnaExportAreaDataDo o1, AnaExportAreaDataDo o2) {
                return o2.getSum().compareTo(o1.getSum());
            }
        };

        Collections.sort(exportAreaDataList,comparator);

        for (int i=0;i<exportAreaDataList.size();i++) {
            JSONObject jsonAreaData = new JSONObject();
            jsonAreaData.put("xh",i+1);
            jsonAreaData.put("area",exportAreaDataList.get(i).getArea());
            jsonAreaData.put("number",exportAreaDataList.get(i).getSum());
            exportAreaDataArray.add(jsonAreaData);
        }
        jsonResult.put("area_number", exportAreaDataArray);
        String result = jsonResult.toJSONString();
        return result;
    }

    private JSONObject getCountryGoodsDetail(ArrayList codes,String countryName){

        Page page = new Page(1,20);
        JSONObject jsonCounty = new JSONObject();

        JSONArray goodArray = new JSONArray();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("tableName", "TB_ANA_DATA_EXPORT_3RD_Y");
        params.put("secondCodes", codes);
        params.put("mainFlag", DimensionFlag.GOODS_TYPE.getCode());
        params.put("secondFlag", DimensionFlag.EXPORT_COUNTRY.getCode());

        List<Ana3rdData> goodsList = ana3rdDataDao.listByParam(params, page);
        for (Ana3rdData ana3rdData : goodsList) {
            JSONObject jsonGood = new JSONObject();
            jsonGood.put("goods_name", ana3rdData.getMainCode());
            jsonGood.put("number", ana3rdData.getSumNum());
            goodArray.add(jsonGood);
        }
        jsonCounty.put("name", countryName);
        jsonCounty.put("goods", goodArray);

        return jsonCounty;
    }
}
